package com.gwc.yy.liuxue.web;

import java.util.List;
import java.io.File;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.util.UriUtils;

import com.google.common.collect.Lists;
import com.gwc.extendsplat.sys.entity.SysAttachfile;
import com.gwc.extendsplat.sys.service.SysAttachfileService;
import com.gwc.yy.liuxue.entity.Student;
import com.gwc.yy.liuxue.entity.YyApplySchool;
import com.gwc.yy.liuxue.service.SchoolService;
import com.gwc.yy.liuxue.service.StudentService;
import com.gwc.yy.liuxue.service.UserExtendService;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;


/**
 * 学生Controller
 * @author 黎俊涛
 * @version 2017-04-13
 */
@Controller
@RequestMapping(value = "${adminPath}/liuxue/student")
public class StudentController extends BaseController {
	@Autowired
	private SystemService systemService;
	@Autowired
	private StudentService studentService;
	@Autowired
	private SysAttachfileService sysAttachfileService;
	@Autowired
	private UserExtendService userExService;
	
	
	
	@ModelAttribute
	public User get(@RequestParam(required=false) String id) {
		if (StringUtils.isNotBlank(id)){
			User user=systemService.getUser(id);
			if(user!=null)
				return new Student();
			return null;
		}else{
			return new Student();
		}
	}
	
	@RequiresPermissions("liuxue:student:edit")
	@RequestMapping(value = "info")
	public String info(User user, Model model) {
		model.addAttribute("student", user);
		return "yy/liuxue/studentinfo";
	}

	@RequiresPermissions("liuxue:student:view")
	@RequestMapping(value = "mystudents")
	public String myStudents(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Student> page = userExService.findMyStudentList(new Page<Student>(request, response), user,UserUtils.getUser().getId());
        model.addAttribute("page", page);
		return "yy/liuxue/myStudentList";
	}
	@RequiresPermissions("liuxue:student:view")
	@RequestMapping(value = "allstudents")
	public String allStudents(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Student> page = userExService.findAllStudentList(new Page<Student>(request, response), user);
        model.addAttribute("page", page);
		return "yy/liuxue/myStudentList";
	}
	@RequiresPermissions("liuxue:student:edit")
	@RequestMapping(value = "form")
	public String form(User user, Model model) {
		
		user=UserUtils.get(user.getId());
		if (user.getCompany()==null || user.getCompany().getId()==null){
			user.setCompany(UserUtils.getUser().getCompany());
		}
		if (user.getOffice()==null || user.getOffice().getId()==null){
			user.setOffice(UserUtils.getUser().getOffice());
		}
		Student s=new Student(user);
		s.setAdviser(systemService.getUser(studentService.getAdvisor(s.getId())));
		model.addAttribute("user", s);
		model.addAttribute("allRoles", systemService.findAllRole());
		return "yy/liuxue/studentForm";
	}
	@RequiresPermissions("liuxue:student:edit")
	@RequestMapping(value = "save")
	public String save(Student s, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {
		User user=systemService.getUser(s.getId());
		
		if(Global.isDemoMode()){
			addMessage(redirectAttributes, "演示模式，不允许操作！");
			return "redirect:" + adminPath + "/sys/user/list?repage";
		}
		// 修正引用赋值问题，不知道为何，Company和Office引用的一个实例地址，修改了一个，另外一个跟着修改。
		user.setCompany(new Office(request.getParameter("company.id")));
		user.setOffice(new Office(request.getParameter("office.id")));
		// 如果新密码为空，则不更换密码
		if (StringUtils.isNotBlank(user.getNewPassword())) {
			user.setPassword(SystemService.entryptPassword(user.getNewPassword()));
		}
		if (!beanValidator(model, user)){
			return form(user, model);
		}
//		if (!"true".equals(checkLoginName(user.getOldLoginName(), user.getLoginName()))){
//			addMessage(model, "保存用户'" + user.getLoginName() + "'失败，登录名已存在");
//			return form(user, model);
//		}
		// 角色数据有效性验证，过滤不在授权内的角色
		List<Role> roleList = Lists.newArrayList();
		List<String> roleIdList = user.getRoleIdList();
		for (Role r : systemService.findAllRole()){
			if (roleIdList.contains(r.getId())){
				roleList.add(r);
			}
		}
		user.setRoleList(roleList);
		// 保存用户信息
		systemService.saveUser(user);
		studentService.save(user.getId(), s.getAdviser().getId());
		// 清除当前用户缓存
		if (user.getLoginName().equals(UserUtils.getUser().getLoginName())){
			UserUtils.clearCache();
			//UserUtils.getCacheMap().clear();
		}
		addMessage(redirectAttributes, "保存用户'" + user.getLoginName() + "'成功");
		return "redirect:" + adminPath + "/liuxue/student/allstudents";
	}
	public String checkLoginName(String oldLoginName, String loginName) {
		if (loginName !=null && loginName.equals(oldLoginName)) {
			return "true";
		} else if (loginName !=null && systemService.getUserByLoginName(loginName) == null) {
			return "true";
		}
		return "false";
	}
	@RequiresPermissions("liuxue:student:edit")
	@RequestMapping(value = "materialSave")
	public String materialSave(SysAttachfile sysAttachfile, HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) throws UnsupportedEncodingException {
		System.out.println("===============================================");
		String basePath=Global.getUserfilesBaseDir()+sysAttachfile.getFilepath().replace("/yueyang", "");
		File file=new File(UriUtils.decode(basePath, "UTF-8"));
		if(file.exists()){
			sysAttachfile.setFilesize(file.length());
		}else{
			return materialForm(sysAttachfile, model);
		}
		if(StringUtils.isEmpty(sysAttachfile.getId()))
			sysAttachfile.setUser(UserUtils.getUser());
		if (!beanValidator(model, sysAttachfile)){
			return materialForm(sysAttachfile, model);
		}
		System.out.println(sysAttachfile.getId()+"==================================");
		sysAttachfileService.save(sysAttachfile);
		addMessage(redirectAttributes, "保存附件成功");
		return "redirect:"+Global.getAdminPath()+"/liuxue/student/material";
	}
	
	@RequiresPermissions("liuxue:student:edit")
	@RequestMapping(value = "materialDelete")
	public String materialDelete(SysAttachfile sysAttachfile, RedirectAttributes redirectAttributes) {
		sysAttachfileService.delete(sysAttachfile);
		addMessage(redirectAttributes, "删除附件成功");
		return "redirect:"+Global.getAdminPath()+"/liuxue/student/material";
	}
	@RequiresPermissions("liuxue:student:view")
	@RequestMapping(value = "material")
	public String material(SysAttachfile sysAttachfile, HttpServletRequest request, HttpServletResponse response, Model model) {
		//model.addAttribute("student", user);
		if(sysAttachfile.getUser()==null||StringUtils.isBlank(sysAttachfile.getUser().getId())){
			sysAttachfile.setUser(UserUtils.getUser());
		}
		Page<SysAttachfile> page = sysAttachfileService.findMaterialPage(new Page<SysAttachfile>(request, response), sysAttachfile); 
		model.addAttribute("page", page);
		return "yy/liuxue/applicationMaterials";
	}
	@RequiresPermissions("liuxue:student:edit")
	@RequestMapping(value = "materialForm")
	public String materialForm(SysAttachfile sysAttachfile, Model model) {
		if(!StringUtils.isEmpty(sysAttachfile.getId()))
			sysAttachfile=sysAttachfileService.get(sysAttachfile.getId());
		model.addAttribute("sysAttachfile", sysAttachfile);
		model.addAttribute("user", UserUtils.getUser());
		return "yy/liuxue/applicationMaterialsForm";
	}
	
}
